package com.juitar.base.enumerator;
/*
 * Created on 19.02.2003
 */

/**
 * @author SKopylov
 */
public class BitFretEnumerator implements IFretEnumerator {

	private int _bits; //bits storage
	
	private int _pos=0;
	private int _mask=1;

	public BitFretEnumerator(int bits) {
		if (bits==0) throw new IllegalArgumentException("No frets are defined");
		_bits = bits;
		reset();
		
	}

	public int get() {
		return _pos-1;
	}

	public boolean next() {
		do {
			_pos++;
			_mask <<= 1; 

			//Out of bound
			if (_mask == 0) return false;
			
			//Bit found
			if ((_mask & _bits) != 0) return true;
			
			//Optimization
			if (_bits >=0 && _mask > _bits) return false;
		} while (true);
	}

	public void reset() {
		_pos = 0;
		_mask = 1;
		//Find first set bit
		while ((_bits & _mask)==0) {
			_mask <<= 1;
			_pos++;
		}
	}
}
